package service

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"mts/trans_srv/internal/domain"
	"mts/trans_srv/internal/repository"
	"mts/trans_srv/utils/rabbitmq"
	"time"
)

type LanService interface {
	Create(ctx context.Context, language domain.Language) error
	Update(ctx context.Context, language domain.Language) error
	Delete(ctx context.Context, langID string) error
	List(ctx context.Context, page, pageSize int) ([]*domain.Language, error)
	UpdateEnabled(ctx context.Context, language *domain.Language) error
	GetByLangID(ctx context.Context, langID string) (*domain.Language, error)
	GetEnableList(ctx context.Context) ([]*domain.Language, error)
	Publish(logData map[string]interface{}) error
	Count(ctx *gin.Context) (int, error)
}
type LanServiceImpl struct {
	repo repository.LanguageRepository
	rmq  *rabbitmq.RabbitMQ
}

func (s *LanServiceImpl) Count(ctx *gin.Context) (int, error) {
	count, err := s.repo.Count(ctx)
	if err != nil {
		return 0, err
	}
	return count, nil
}

func NewLanguageService(repo repository.LanguageRepository, rmq *rabbitmq.RabbitMQ) LanService {
	return &LanServiceImpl{repo: repo, rmq: rmq}
}

func (s *LanServiceImpl) List(ctx context.Context, page, pageSize int) ([]*domain.Language, error) {
	list, err := s.repo.List(ctx, page, pageSize)
	if err != nil {
		return nil, err
	}
	return list, nil
}
func (s *LanServiceImpl) GetEnableList(ctx context.Context) ([]*domain.Language, error) {
	languages, err := s.repo.GetEnabledLanguages(ctx)
	if err != nil {
		return nil, err
	}
	return languages, nil
}
func (s *LanServiceImpl) Publish(logData map[string]interface{}) error {
	logData["timestamp"] = time.Now()

	err := s.rmq.Publish(
		logData,
	)
	if err != nil {
		zap.S().Errorf("Error publishing log: %v", err)
		return err
	}
	return nil
}
func (s *LanServiceImpl) UpdateEnabled(ctx context.Context, language *domain.Language) error {
	err := s.repo.UpdateEnabled(ctx, language)
	if err != nil {
		fmt.Println(fmt.Errorf("更新语言启用状态失败: %w", err))
		return err
	}
	return nil
}

func (s *LanServiceImpl) Create(ctx context.Context, language domain.Language) error {
	err := s.repo.Create(ctx, language)
	if err != nil {
		return err
	}
	return nil
}

func (s *LanServiceImpl) GetByLangID(ctx context.Context, langID string) (*domain.Language, error) {
	language, err := s.repo.FindByLangID(ctx, langID)
	if err != nil {
		return nil, err
	}
	return language, nil
}

func (s *LanServiceImpl) Update(ctx context.Context, language domain.Language) error {
	err := s.repo.Update(ctx, language)
	if err != nil {
		return err
	}
	return nil
}

func (s *LanServiceImpl) Delete(ctx context.Context, langID string) error {
	err := s.repo.Delete(ctx, langID)
	if err != nil {
		return err
	}
	return nil
}
